package com.andaily.domain.dto.user;

import com.andaily.domain.user.User;
import org.apache.commons.lang.StringUtils;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.Arrays;
import java.util.Collection;

/**
 * @author Shengzhao Li
 */
public class AndailyUserDetails implements UserDetails {

    protected static final String ROLE_PREFIX = "ROLE_";
    protected static final GrantedAuthority DEFAULT_USER_ROLE = new SimpleGrantedAuthority(ROLE_PREFIX + "USER");

    protected String userGuid;
    protected String username;
    protected String password;
    protected String nickName;

    public AndailyUserDetails(User user) {
        this.userGuid = user.guid();
        this.username = user.username();
        this.password = user.password();
        this.nickName = user.nickName();
    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        return Arrays.asList(DEFAULT_USER_ROLE);
    }

    @Override
    public String getPassword() {
        return password;
    }

    @Override
    public String getUsername() {
        return username;
    }

    public String getUserGuid() {
        return userGuid;
    }

    /**
     * Call by dashboard page
     *
     * @return User nick name
     */
    public String getNickName() {
        if (StringUtils.isNotBlank(nickName)) {
            return nickName;
        }
        return username;
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return true;
    }

    @Override
    public String toString() {
        return "AndailyUserDetails{" +
                "userGuid='" + userGuid + '\'' +
                ", username='" + username + '\'' +
                ", nickName='" + nickName + '\'' +
                '}';
    }
}
